<!-- 新增角色 -->
<template>
  <div>
    <el-card>
      <el-form
        ref="ruleFormRef"
        v-loading="loading"
        :model="ruleForm"
        :rules="rules"
        label-position="top"
        style="margin: 15px 0 0 10px"
      >
        <el-form-item label="角色名称" prop="name">
          <el-input v-model="ruleForm.name" placeholder="请输入角色名称" style="width: 300px" />
        </el-form-item>
        <el-form-item label="权限配置" prop="menuIds">
          <el-tree
            ref="treeRef"
            :data="role"
            show-checkbox
            node-key="id"
            :props="defaultProps"
            :default-checked-keys="checkedKeys"
            @check-change="onCheckChange"
          />
        </el-form-item>
        <el-form-item>
          <el-button @click="router.push('/system/role')">取消</el-button>
          <el-button type="primary" @click="submit">确定</el-button>
        </el-form-item>
      </el-form>
    </el-card>
  </div>
</template>
<script setup lang="ts">
import { reactive, ref, onMounted } from "vue";
import { Delete, Edit, Message, Document, Search, Refresh } from "@element-plus/icons-vue";
import router from "@/router";
import { accountAddParams, CompanyAdd, CompanyGet, CompanyUpdate } from "@/api/system/Role/Role";
import { AddListData } from "@/api/system/Role/type";
import { getMenuList } from "@/api/personel/position/position";
import { buildTree } from "@/utils/treeUtil";
import type { ComponentSize, FormInstance, FormRules, ElTree } from "element-plus";
import type Node from "element-plus/es/components/tree/src/model/node";
import { on } from "events";
import { MenuData } from "@/api/personel/position/type";
const route = useRoute();
const loading = ref(false);
const formSize = ref<ComponentSize>("default");

const menuList = ref<AnyObject[]>([]);
// const formData = ref<any>({});

// interface RuleForm {
//   name: string;
// }
const ruleForm = reactive<accountAddParams>({
  id: 0,
  name: "",
  menuIds: [],
});

const role = ref<MenuData[]>([]);

const getList = async () => {
  let res = await getMenuList();
  console.log(res);
  // buildTree(res)
  role.value = buildTree(res.list);
  console.log(role.value);
};
onMounted(() => {
  getList();
});
const checkedKeys = ref<number[]>([]);
// const treeRef = ref();
const onCheckChange = (data: any, checked: boolean) => {
  console.log("342232", data);
  const onCheckred = (children: MenuData[]) => {
    children.forEach((chrid) => {
      if (!ruleForm.menuIds.includes(chrid.id)) {
        ruleForm.menuIds.push(chrid.id);
      }
      if (chrid.children) {
        onCheckred(chrid.children);
      }
    });
  };
  if (checked) {
    if (!ruleForm.menuIds.includes(data.id)) {
      ruleForm.menuIds.push(data.id);
    }
    if (data.children) {
      onCheckred(data.children);
    }
  } else {
    ruleForm.menuIds = ruleForm.menuIds.filter((id) => id !== data.id);
    if (data.children) {
      data.children.forEach((child: any) => {
        ruleForm.menuIds = ruleForm.menuIds.filter((id) => id !== child.id);
        if (child.children) {
          child.children.forEach((grandChild: any) => {
            ruleForm.menuIds = ruleForm.menuIds.filter((id) => id !== grandChild.id);
          });
        }
      });
    }
  }
  ruleForm.menuIds = [...new Set(ruleForm.menuIds)];
  console.log(ruleForm.menuIds);
};

// 树形控件
interface Tree {
  id: number;
  label: string;
  children?: Tree[];
}

const treeRef = ref<InstanceType<typeof ElTree>>();

const defaultProps = {
  label: "name",
  value: "id",
};
// 获取表单单条数据
// let ruleForm = reactive<AddListData>({
//   id: 0,
//   name: "",
//   menuIds: [],
// });
const CompanyId = ref();
const getCompany = async () => {
  let res = await CompanyGet(CompanyId?.value);
  Object.assign(ruleForm, res);
};
// 添加
const submitForm = async () => {
  const companySubmit = {
    ...ruleForm,

    name: String(ruleForm.name),
  };
  let res = await CompanyAdd(companySubmit);
  ElMessage.success("添加成功");
  router.push("/system/Role");
};
const submit = async () => {
  ruleFormRef.value?.validate(async (valid) => {
    if (valid) {
      ruleForm.id === 0 ? await submitForm() : await upload();
    }
  });
};
// 修改
const upload = async () => {
  let res = await CompanyUpdate(ruleForm);
  ElMessage.success("修改成功");
  router.push("/company/list");
};

onMounted(() => {
  getCompany();
  CompanyId.value = route.query.id;
});

const ruleFormRef = ref<FormInstance>();
const rules = reactive<FormRules<AddListData>>({
  name: [{ required: true, message: "请输入角色名称", trigger: "blur" }],
  menuIds: [{ required: true, message: "请选择权限配置", trigger: "blur" }],
});
</script>
<style scoped>
.text {
  margin-top: 30px;
}

.btn {
  margin-top: 20px;
}
</style>
